<template>
  <div class='ele-body ele-body-card'>
    <!-- 顶部卡片 -->
    <a-card
      :bordered='true'
      :body-style="{padding: '20px'}">
      <div class='ele-cell workplace-user-card'>
        <div class='ele-cell-content ele-cell'>
          <a-progress :width='70' type='circle' :percent='100' :format="() => '设备'" />
          <div class='ele-cell-content'>
            <h4 class='ele-elip'>设备号：{{ data.recordId }}</h4>
            <div class='ele-elip ele-text-secondary'>
              <clock-circle-outlined />
              <em>{{ data.deviceTime }}</em>
            </div>
          </div>
        </div>
      </div>
    </a-card>

    <a-card
      :bordered='true'
      :body-style="{padding: '20px'}">
      <a-form
        ref='form'
        :model='form'
        :rules='rules'
        :label-col='{ md: { span: 10 }, sm: { span: 24 } }'
        :wrapper-col='{ md: { span: 14 }, sm: { span: 24 } }'
        @submit='saveConfigToCmdQueue'
      >
        <a-divider>卷帘升降手动设置</a-divider>
        <a-row :gutter='8'>
          <a-col :md='24' :sm='24' :xs='24'>
            <a-form-item label='远程直控模式下卷帘的开度(0到100， 0代表卷帘全展开，100代表卷帘全卷起来):' name='rollOpeningSet'>
              <a-input style="width: 70%" v-model:value='form.rollOpeningSet' placeholder='0到100' allow-clear />
            </a-form-item>
          </a-col>
        </a-row>

        <a-row>
          <a-col :md='1' :sm='24' :xs='24' />

          <a-col :md='2' :sm='24' :xs='24'>
            <a-form-item :wrapper-col='{ span: 12, offset: 5 }'>
              <a-button type='primary' html-type='submit' :loading='iconLoading' v-permission="['PROPERTY_DEVICELIST_MGR_ROLLERSHADES_UPDOWN_SET_BUTTON']">
                保存并同步
              </a-button>
            </a-form-item>
          </a-col>
          <a-col :md='1' :sm='24' :xs='24' />
          <a-col :md='2' :sm='24' :xs='24'>
            <a-form-item :wrapper-col='{ span: 12, offset: 5 }'>
              <a-button v-permission="['PROPERTY_DEVICELIST_MGR_ROLLERSHADES_UPDOWN_CONFIG_READ_BUTTON']" type='primary' html-type='button' @click='getParamsActionToCmdQueue' :loading='getParamsLoading'>
                读取设备的配置
              </a-button>
            </a-form-item>
          </a-col>
          <a-col :md='1' :sm='24' :xs='24' />
          <a-col :md='2' :sm='24' :xs='24'>

          </a-col>
          <a-col :md='1' :sm='24' :xs='24' />
          <a-col :md='2' :sm='24' :xs='24'>
          </a-col>
          <a-col :md='2' :sm='24' :xs='24' />
          <a-col :md='10' :sm='24' :xs='24' />
        </a-row>
      </a-form>
    </a-card>
  </div>
</template>

<script>
import ClockCircleOutlined from '@ant-design/icons-vue/lib/icons/ClockCircleOutlined';
import { message } from 'ant-design-vue';
import {DeviceCommandDownQueueApi} from '@/api/property/DeviceCommandDownQueueApi';
import {DeviceRollershadesConfigApi} from "@/api/property/rollershades/DeviceRollershadesConfigApi";


export default {
  name: 'DeviceRollershadesConfigUpdownSwitch',
  components: {
    ClockCircleOutlined
  },
  props: {
    data: Object
  },
  async mounted() {
  },
  async created() {
    await this.init();
  },
  data() {
    return {
      form: {},
      sourceForm: {},
      switchform: {},
      rules: {},
      iconLoading: false,
      loadTimer: null,

      restartIconLoading : false,
      restartLoadTimer : '',
      getParamsLoading : false,
      getParamsTimer : '',

      clearParamsLoading : false,
      clearParamsTimer : null
    };
  },
  methods: {
    async init() {
      let _conf = await DeviceRollershadesConfigApi.detail({ 'recordId': this.data.recordId });
      if (_conf) {
        this.form = _conf;
        this.switchform.masterSwitchCheck = (_conf.masterSwitch == 1) ? true : false;
        console.log(this.form);
        this.sourceForm = Object.assign({}, _conf);
      }
    },
    masterSwitchChange(checked) {
      console.log(checked);
      this.switchform.masterSwitchCheck = checked;
    },

    checkProcess(sceneDictate, clearCallback, callback) {
      let params = {
        recordId: this.data.recordId,
        sceneDictate: sceneDictate
      };
      let result = DeviceCommandDownQueueApi.workingDetail(params);
      result
        .then(result => {
          if (!result || !result.dcdqId) { //处理完成了
            clearCallback && clearCallback(); //去掉菊花+清除循环调用
            callback && callback(); //用户自定义
          }
        })
        .catch(() => {
          clearCallback && clearCallback(); //去掉菊花+清除循环调用
        });
    },


    //保存配置
    clearConfigProcess(){
      this.iconLoading = false;
      clearInterval(this.loadTimer);
    },
    checkConfigProcess()
    {
      let that = this;
      this.checkProcess(9992, this.clearConfigProcess, function(){
        that.init();
      });
    },
    saveConfigToCmdQueue()
    {
      let workerDetailparams = {
        recordId: this.data.recordId,
        sceneDictate: 9992
      };
      let that = this;
      let existWorkerResult = DeviceCommandDownQueueApi.workingDetail2(workerDetailparams);
      existWorkerResult
        .then(workResult => {
          console.log(workResult);
          if (!workResult || !workResult.dcdqId) { //处理完成了
            that.save();
          } else {
            message.error('上一个配置还在推送中，请稍后重试');
            return;
          }
        })
        .catch((e) => {
          message.error(e);
        });
    },
    /**
     * 保存和编辑
     * 写到队列，队列发送完回写到原配置
     * @author cancan
     * @date 2022/03/04 21:15
     */
    save() {
      this.form.masterSwitch = this.switchform.masterSwitchCheck ? 1 : 2;
      // 校验表单
      //await this.$refs.form.validate();

      // 修改加载框为正在加载
      this.loading = true;
      let updateForm = this.form;
      delete updateForm.heartIntervalTime;

      let updateData = {
        old: this.sourceForm,
        update: {
          "autoMode" : 1,
          "rollOpeningSet" : updateForm.rollOpeningSet
        }
      };
      let updateDataRecord = {
        recordId: this.data.recordId,
        templateCode: 'rollershades',
        updateData: JSON.stringify(updateData),
        sceneDictate : 9992
      };

      let result = DeviceCommandDownQueueApi.add(updateDataRecord);
      result
        .then(result => {
          // 移除加载框
          this.loading = false;
          // 提示添加成功
          message.success(result.message);

          this.iconLoading = true; //转圈
          this.loadTimer = setInterval(this.checkConfigProcess, 5000);
        })
        .catch(() => {
          this.loading = false;
        });
    },



    //读取参数
    clearGetParamsProcess(){
      this.getParamsLoading = false;
      clearInterval(this.getParamsTimer);
    },
    checkGetParamsProcess()
    {
      let that = this;
      this.checkProcess(56, this.clearGetParamsProcess, function(){
        that.init();
      });
    },
    getParamsActionToCmdQueue()
    {
      let workerDetailparams = {
        recordId: this.data.recordId,
        sceneDictate: 56
      };
      let that = this;
      let existWorkerResult = DeviceCommandDownQueueApi.workingDetail2(workerDetailparams);
      existWorkerResult
        .then(workResult => {
          console.log(workResult);
          if (!workResult || !workResult.dcdqId) { //处理完成了
            that.getParams();
          } else {
            message.error('上一个配置还在推送中，请稍后重试');
            return;
          }
        })
        .catch((e) => {
          message.error(e);
        });
    },

    getParams() { //读取配置
      this.loading = true;
      let updateData = {
        old: '',
        update: '',
      };
      let updateDataRecord = {
        recordId: this.data.recordId,
        templateCode: 'rollershades',
        updateData: JSON.stringify(updateData),
        dictate : 56,
        sceneDictate : 56
      };

      let result = DeviceCommandDownQueueApi.add(updateDataRecord);
      result
        .then(result => {
          // 移除加载框
          this.loading = false;
          // 提示添加成功
          message.success(result.message);

          this.getParamsLoading = true; //转圈
          this.getParamsTimer = setInterval(this.checkGetParamsProcess, 5000);
        })
        .catch(() => {
          this.loading = false;
        });
    },
  }
};
</script>
<style scoped>
/** 用户卡片 */
.workplace-user-card .ele-cell-content {
  overflow: hidden;
}

.workplace-user-card h4 {
  margin-bottom: 6px;
}
</style>
